import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dragable_flutter_list/dragable_flutter_list.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:device_calendar/device_calendar.dart';
import 'package:vibrate/vibrate.dart';
import 'package:my_todo/util/todo_prop.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import 'dart:async';
import 'dart:convert';

class TodoPageFinal extends StatefulWidget {
  @override
  TodoPageFinalState createState() {
    // TODO: implement createState
    return new TodoPageFinalState();
  }
}

class TodoPageFinalState extends State<TodoPageFinal> {
  Calendar _selectedCalendar;
  List<Calendar> _calendars;
  DeviceCalendarPlugin _deviceCalendarPlugin = new DeviceCalendarPlugin();
  //日历插件相关
  final _slidableController = new SlidableController();
  final _todoController = new TextEditingController();

  var _todoItems = new List<Todo>();
  var _todoJsonItems = new List<String>();

  bool _canVibrate = false;

  String _todoJsonList = "null";
  var flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    get();
    _retrieveCalendars();

    var initializationSettingsAndroid =
        new AndroidInitializationSettings('app_icon');
    var initializationSettingsIOS =
        new IOSInitializationSettings(onDidReceiveLocalNotification: null);
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: null);
    //debugPrint ("got it");
  }

  @override
  Widget build(BuildContext context) {
    _todoController.addListener(() {});
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "Todo",
          style: new TextStyle(
              fontWeight: FontWeight.w800, letterSpacing: 1.1, fontSize: 25.0),
        ),
      ),
      body: _todoItems.length == 0 ? _todoClear() : _listViewer(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.add),
        onPressed: () {
          _askedToLoad();
          //_handleTap("testing");
        },
        backgroundColor: Colors.deepOrange,
      ),
    );
  }

  Widget _todoClear() {
    return new Center(
      child: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new Container(
            width: 300.0,
            height: 300.0,
            child: new Image.asset(
              'assets/img/todo_cleared.png',
              fit: BoxFit.scaleDown,
            ),
          ),
          new Text(
            "无事一身轻!",
            style: new TextStyle(color: Colors.grey),
          ),
        ],
      ),
    );
  }

  Widget _todoItem(int i, bool isTop) {
    if (isTop == false) {
      return new SizedBox(
        height: 80.0,
        child: new Slidable(
          controller: _slidableController,
          child: new ListTile(
            title: new Text(
              _todoItems[i].todoEvent,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: new Text(_todoItems[i].date),
          ),
          delegate: new SlidableDrawerDelegate(),
          actionExtentRatio: 0.25,
          secondaryActions: <Widget>[
            new IconSlideAction(
              icon: Icons.done,
              color: Colors.green,
              onTap: () async {
                bool canVibrate = await Vibrate.canVibrate;
                if (canVibrate) Vibrate.feedback(FeedbackType.medium);
                _removeTodoItem(i);
              },
              caption: "完成任务",
            ),
            new IconSlideAction(
              icon: Icons.alarm,
              color: Colors.orangeAccent,
              onTap: () => _setAlarm(i),
              caption: "添加提醒",
            ),
            new IconSlideAction(
              icon: Icons.vertical_align_top,
              color: Colors.redAccent,
              onTap: () => _setTop(i),
              caption: "置顶事件",
            ),
          ],
        ),
      );
    } else
      return new SizedBox(
        height: 80.0,
        child: new Slidable(
          controller: _slidableController,
          child: new ListTile(
            title: new Text(
              _todoItems[i].todoEvent,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: new Text(_todoItems[i].date),
          ),
          delegate: new SlidableDrawerDelegate(),
          actionExtentRatio: 0.25,
          secondaryActions: <Widget>[
            new IconSlideAction(
              icon: Icons.done,
              color: Colors.green,
              onTap: () async {
                bool canVibrate = await Vibrate.canVibrate;
                _canVibrate = canVibrate;
                if (canVibrate) Vibrate.feedback(FeedbackType.medium);
                _removeTodoItem(i);
              },
              caption: "完成任务",
            ),
            new IconSlideAction(
              icon: Icons.alarm,
              color: Colors.orangeAccent,
              onTap: () => _setAlarm(i),
              caption: "添加提醒",
            ),
            new IconSlideAction(
              icon: Icons.vertical_align_top,
              color: Colors.redAccent,
              onTap: () => _cancelTop(i),
              caption: "取消置顶",
            ),
          ],
        ),
      );
  }

  Widget _listViewer() {
    return new DragAndDropList(
      _todoItems.length,
      itemBuilder: (context, index) {
        if (index < _todoItems.length)
          return new Container(
            child: new Column(
              children: <Widget>[
                new Divider(),
                _todoItem(index, _todoItems[index].isTop),
              ],
            ),
          );
        //debugPrint("${_todoItems[index]}");
      },
      onDragFinish: (before, after) {
        print('on drag finish $before $after');
        Todo data = _todoItems[before];
        _todoItems.removeAt(before);
        _todoItems.insert(after, data);
        String _jsonData = _todoJsonItems[before];
        _todoJsonItems.removeAt(before);
        _todoJsonItems.insert(after, _jsonData);
        save();
        if (_canVibrate) Vibrate.feedback(FeedbackType.light);
      },
      canDrag: (index) {
        return index != 3; //disable drag for index 3
      },
      canBeDraggedTo: (one, two) => true,
      dragElevation: 2.0,
    );
  }

  Widget _customTextField() {
    return new TextField(
      controller: _todoController,
      decoration: InputDecoration(
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(50.0)),
        hintText: "等待输入...",
        hintStyle: TextStyle(fontWeight: FontWeight.bold),
      ),
    );
  }

  void _removeTodoItem(int index) {
    setState(() {
      _todoItems.removeAt(index);
      _todoJsonItems.removeAt(index);
      debugPrint("$index deleted"); //输出被删除的序号
    });
    save();
    Fluttertoast.showToast(
        msg: "任务已完成",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  void _handleTap(String text, bool toastJudge) {
    setState(() {
      Todo _todoTmp = new Todo(
          todoEvent: text, date: DateUtil.getNowDateStr(), isTop: false);
      _todoItems.add(_todoTmp);
      String _todoJson = json.encode(_todoTmp);
      _todoJsonItems.add(_todoJson);
    });
    save();
    if (toastJudge == true)
      Fluttertoast.showToast(
          msg: "添加成功",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.redAccent,
          textColor: Colors.white,
          fontSize: 16.0);
  }

  void handleGet(Todo t) {
    setState(() {
      _todoItems.add(t);
      String _jsonTmp = json.encode(t);
      _todoJsonItems.add(_jsonTmp);
      print(_todoItems.length);
    });
  }

//get过来的json有很大的问题,现在没了@2019.3.3 19：33
  get() async {
    List<String> todo;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    todo = prefs.getStringList(_todoJsonList);
    print(todo);
    if (todo.isNotEmpty) {
      setState(() {
        todo.forEach((i) {
          Map _todoMap = json.decode(i);
          Todo _todoFromJson = new Todo.fromJson(_todoMap);
          handleGet(_todoFromJson);
        });
      });
    } else
      print("get nothing");
  }

  save() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList(_todoJsonList, _todoJsonItems);
    print("存储todoJsonItems为$_todoJsonItems");
  }

  _setTop(int index) {
    setState(() {
      Todo temp = _todoItems.elementAt(index);
      temp.isTop = true;
      _todoItems.removeAt(index);
      _todoItems.insert(0, temp);

      String _jsonTmp = json.encode(temp);
      _todoJsonItems.removeAt(index);
      _todoJsonItems.insert(0, _jsonTmp);
      save();
      Fluttertoast.showToast(
          msg: "置顶成功",
          backgroundColor: Colors.blueAccent,
          textColor: Colors.white);
    });
  }

  _cancelTop(int index) {
    setState(() {
      Todo temp = _todoItems.elementAt(0);
      temp.isTop = false;
      _todoItems.removeAt(0);
      _todoItems.insert(_todoItems.length, temp);
      var _jsonTmp = json.encode(temp);
      _todoJsonItems.removeAt(0);
      _todoJsonItems.insert(_todoJsonItems.length, _jsonTmp);
      save();
      Fluttertoast.showToast(
          msg: "取消置顶成功",
          backgroundColor: Colors.blueAccent,
          textColor: Colors.white);
    });
  }

  _setAlarm(int index) async {
    await _retrieveCalendarEvents(_calendars[0].id);
    setState(() {
      _selectedCalendar = _calendars[0];
    });
    final _selected = await _selectTime(context);
    if(_selected != null) {
      final eventToCreate = new Event(_selectedCalendar.id);
      eventToCreate.title = _todoItems[index].todoEvent.toString();
      eventToCreate.start = _selected;
      eventToCreate.end = _selected.add(new Duration(hours: 1));

      final createEventResult =
      await _deviceCalendarPlugin.createOrUpdateEvent(eventToCreate);
      if (createEventResult.isSuccess &&
          (createEventResult.data?.isNotEmpty ?? false)) {
        _retrieveCalendarEvents(_selectedCalendar.id);
      }

      await _showNotification(_selected, index);

        Fluttertoast.showToast(
            msg: "已创建提醒",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.orangeAccent,
            textColor: Colors.white,
            fontSize: 16.0);
    }
    else
      Fluttertoast.showToast(
          msg: "创建提醒失败",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.orangeAccent,
          textColor: Colors.white,
          fontSize: 16.0);

  }

  Future _showNotification(DateTime time, int index) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        'todo_remind_channel_1', 'todo_remind_channel', 'remind user things',
        color: const Color.fromARGB(255, 255, 0, 0),
        importance: Importance.Max,
        priority: Priority.High);
    var iOSPlatformChannelSpecifics =
        new IOSNotificationDetails(sound: "slow_spring_board.aiff");
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.schedule(
        0,
        '记得去 ${_todoItems[index].todoEvent} 呐！',
        '(ง •_•)ง',
        time,
        platformChannelSpecifics);
  }

  void _retrieveCalendars() async {
    var permissionsGranted = await _deviceCalendarPlugin.hasPermissions();
    if (permissionsGranted.isSuccess && !permissionsGranted.data) {
      permissionsGranted = await _deviceCalendarPlugin.requestPermissions();
      if (!permissionsGranted.isSuccess || !permissionsGranted.data) {
        return;
      }
    }

    final calendarsResult = await _deviceCalendarPlugin.retrieveCalendars();
    setState(() {
      _calendars = calendarsResult?.data;
    });
  }

  Future _selectTime(BuildContext context) async {
    DateTime _date;
    TimeOfDay _time;
    DateTime _datePicker = await showDatePicker(
        context: context,
        initialDate: new DateTime.now(),
        firstDate: new DateTime(2016),
        lastDate: new DateTime(2060));
    TimeOfDay _timePicker = await showTimePicker(
        context: context, initialTime: new TimeOfDay.now());
    if (_datePicker != null && _datePicker != DateTime.now()) {
      _date = _datePicker;
    }
    if (_timePicker != null && _timePicker != TimeOfDay.now()) {
      _time = _timePicker;
    }
    if(_date != null && _time != null){
    final DateTime _customize = new DateTime(
        _date.year, _date.month, _date.day, _time.hour, _time.minute, 0, 0, 0);
    return _customize;
    }
    else
      return null;
  }

  Future _retrieveCalendarEvents(String calendarId) async {
    try {
      final startDate = new DateTime.now().add(new Duration(days: -30));
      final endDate = new DateTime.now().add(new Duration(days: 30));
    } catch (e) {
      print(e);
    }
  }

  Future<void> _askedToLoad() async {
    return showDialog<Null>(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: new Text("待办事项输入"),
            titlePadding: EdgeInsets.fromLTRB(70.0, 20.0, 0.0, 0.0),
            content: _customTextField(),
            actions: <Widget>[
              new FlatButton(
                child: new Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              new FlatButton(
                child: new Text('确定'),
                onPressed: () {
                  if (_todoController.text == "") {
                    Navigator.of(context).pop();
                  } else {
                    Navigator.of(context).pop();
                    _handleTap(_todoController.text, true);
                    _todoController.text = "";
                  }
                },
              )
            ],
          );
        });
  }
}
